try {
  const { type, params: { operation, data } } = $event;
  const gis = this.getApiPage().getApiWidgetByAliasName('三维组件');
  const queryManage = this.pageObj.getApiWidgetByAliasName('queryManage')?.widgetObj;
  const prefix = this.pageObj.getVariables().find(v => v.name === "environmentType")?.value;
  console.log('$event: => ', $event);

  const requestGet = (url) => {
    return fetch(url, { headers: { "Content-Type": "application/json" } }).then(res => res.json())
  };
  const requestPost = (url, body) => {
    const option = {
      method: 'POST',
      headers: { 'Content-type': 'application/json' },
      body: JSON.stringify(body),
    }
    return fetch(url, option).then(res => res.json())
  };


  this.pageObj.setVariables([{ name: 'screen_params', value: JSON.stringify(data) }]);
  console.log('screen_params: => ', data)


  const queryDrillDetail = () => {
    return queryManage.queryDrillDetail(data.id).then(res => {
      const { xCoordinate, yCoordinate, zCoordinate, startTime, endTime } = res;
      return {
        ...res,
        drillDatetimeRange: `${startTime} 至 ${endTime}`,
        occurrencePlace: `${xCoordinate} , ${yCoordinate} , ${zCoordinate}`,
      };
    });
  };

  const showDrillDetail = () => {
    const $formDetail = this.getApiPage().getApiWidgetByAliasName('judge-content');
    const $img = this.getApiPage().getApiWidgetByAliasName('detail-img');
    const btns = this.pageObj.getApiWidgetByAliasName('modal-btns')?.widgetObj;
    const process = this.pageObj.getVariables().find(v => v.name === 'whetherProcess')?.value || 0;
    const { eventDetails } = data || {};

    return queryDrillDetail().then(formData => {
      const { xCoordinate, yCoordinate, zCoordinate } = formData;
      gis.widgetObj.setIconPosition({ right: 420, top: 100 });

      // 关闭所有编辑组件
      this.getApiPage().getApiWidgetsByClassName('edit')?.forEach(v => v.hideWidget());
      // 显示所有的 详情组件。
      this.getApiPage().getApiWidgetsByClassName('detail')?.forEach(v => v.showWidget());

      formData.pointId = `${xCoordinate},${yCoordinate},${zCoordinate}`
      formData.eventPoint = `${xCoordinate},${yCoordinate},${zCoordinate}`
      $formDetail.widgetObj._option.dataSource = formData;
      $formDetail.widgetObj._option.isDetail = true;
      $formDetail.widgetObj.render();

      // if (+process !== 1) {
      // 不是已结束，就都显示按钮组
      // this.getApiPage().getApiWidgetByAliasName('detail-toggle')?.showWidget()
      // }

      var personCountVar = $($formDetail.__box).find("#d-personCount");

      if (personCountVar && personCountVar[0]) {
        personCountVar[0].innerText = "当前参演人员" + (formData.personCount) + "位";
      }

      var drillStateVar = $($formDetail.__box).find("#d-drillState");

      if (drillStateVar && drillStateVar[0]) {
        drillStateVar[0].innerText = formData.drillState;
      }

      // 编辑状态
      $formDetail.widgetObj.resetForm('form_19');
      $formDetail.widgetObj.setFormData('form_19', formData);
      // 详情状态
      // $formDetail.widgetObj.resetForm('form_20');

      if (+formData.disableFlag === 2 || +formData.disableFlag === 4) {
        btns?.renderJoinDrill();
      } else {
        if (+formData.disableFlag !== 1 && +formData.disableFlag !== 3) btns?.renderDrill();
      }
      if (+formData.disableFlag !== 1 && +formData.disableFlag !== 3) btns?.show();

      if (eventDetails) {
        let info;
        try {
          info = JSON.parse(eventDetails)
        } catch (e) {
          console.error(e)
        }
        console.log('info', [{ data: [{ src: info?.thumbnailPath }] }]);

        if (info?.thumbnailPath) {
          const srcArr = info.thumbnailPath.split(',').map(v => ({ src: v }));
          $img.widgetObj.setData([{ data: srcArr }]);
          $img.widgetObj.render();
        } else {
          $img.widgetObj.setData([{ data: [] }]);
          $img.widgetObj.render();
        }
      }

      return formData
    });
  };

  function createAssessmentTemp(detail, { assessmentRecords, comprehensiveEvaluation }) {
    const records = assessmentRecords.map(({ quota, score, content }) => (`
      <dd class="layui-row">
        <div class="layui-col-xs5">${quota}：${score}分</div>
        <div class="layui-col-xs7">内容：${content || ''}</div>
      </dd>
    `));

    return (`
      <dl class="vt-rate">
        <dl class="assessment-content">
          <dt class="assessment-title">演练信息：</dt>
          <dd>所属区域：${detail.eventRange          || ''}</dd>
          <dd>演练时间：${detail.drillDatetimeRange  || ''}</dd>
          <dd>演练来源：${detail.source              || ''}</dd>
          <dd>演练名称：${detail.drillName           || ''}</dd>
          <dd>演练类型：${detail.eventType           || ''}</dd>
          <dd>演练等级：${detail.eventGrade          || ''}</dd>
          <dd>演练位置：${detail.drillLocation       || ''}</dd>
          <dd>演练性质：${detail.eventQuality        || ''}</dd>
          <dd>演练范围：${detail.eventRange          || ''}</dd>
          <dd>演练目的：${detail.drillSake           || ''}</dd>
          <dd>演练状态：${detail.disableFlag         || ''}</dd>
          <dd>演练人员：${detail.personCount         || ''}人</dd>
          <dd>演练内容：${detail.drillContent        || ''}</dd>
        </dl>
        <dl class="assessment-content">
          <dt class="assessment-title">
            <span>演练评估：</span>
            <div class="assessment-sale">综合评分：${comprehensiveEvaluation}分</div>
          </dt>
          ${ records.join('') }
        </dl>
      </dl>
      <style>
        .assessment-content {
          margin: 10px;
        }
        .assessment-content .assessment-title {
          position: relative;
          font-size: 18px;
          font-weight: bold;
          color: #63e7f4;
        }
        .assessment-content .assessment-title .assessment-sale {
          position: absolute;
          font-size: 26px;
          right: 10px;
          top: 0;
        }
      </style>
    `)
  }

  function showAssessment(cb) {
    requestGet(`/${prefix}SummaryAssessmentSV/assessmentRecord/selectByEventId?eventId=${data.id}`).then(({ result, success }) => {
      if (success && result.assessmentRecords?.length) {
        queryDrillDetail().then(detail => {
          console.log(detail);
          const temp = createAssessmentTemp(detail, result);
          cb && cb(temp, true);
        });
      } else {
        cb && cb(`<div class="vt-empty">未填写演练评估</div>`);
      }
    });
  }
  // 获取当前演练人员列表
  const requestPerson = (eventId) => (
      requestGet(`/${prefix}SummaryAssessmentSV/emergencyRecord/recordFilterCriteria?eventId=${eventId}`).then(({ success, result }) => {
        console.log(this, { success, result });
        if (success && result && Array.isArray(result.personList)) return result.personList.map(item => ({
          name: item, value: item,
        }))
      })
  )

  const openRecord = () => {
    const timeline = this.getApiPage().getApiWidgetByAliasName('timelineVertical');
    const formRecord = this.getApiPage().getApiWidgetByAliasName('formRecord');
    const summary = this.getApiPage().getApiWidgetByAliasName('summary');
    const baseForm = this.getApiPage().retrievePlugin('base-forms');

    summary.hideWidget();
    timeline.showWidget();
    formRecord.showWidget();
    showDrillDetail();

    // 重置演练记录搜索条件
    formRecord.widgetObj.resetForm(formRecord.widgetObj._option.instanceName);
    baseForm.resetForm(formRecord.widgetObj._option.instanceName);
    // 成员
    requestPerson(data.id).then((result) => {
      if (result) {
        formRecord.widgetObj.asyncSelectOptions('personName', result);
      }
    })

    if (timeline && timeline.widgetObj) {
      const { setUpdateStatus } = timeline.widgetObj;

      if (setUpdateStatus) setUpdateStatus(data.whetherProcess !== 1);
      // if (setVariable) setVariable('timeline_event_id', data.id);
      // if (setVariable) setVariable('eventId', data.id);
      requestPost(`/${prefix}SummaryAssessmentSV/emergencyRecord/planHandleProcessDetailByReq`, { eventId: data.id }).then(({ result, success }) => {
        if (success && Array.isArray(result)) {
          timeline.widgetObj.dataSource = result;
          timeline.widgetObj.render();
        }
        console.log('演练记录： =》 ', { result, success })
      })
    } else {
      layer?.msg('打开演练记录失败！');
    }
  }

  if (type === 'page') {
    /**
     * 切换分页
     */
    const panel = this.pageObj.getApiWidgetByAliasName('event-panel')?.widgetObj;
    const type = this.pageObj.getVariables().find(v => v.name === 'panelType')?.value || 0;
    const process = this.pageObj.getVariables().find(v => v.name === 'whetherProcess')?.value || 0;
    const _form = this.getApiPage().retrievePlugin('base-forms');
    const searchText = _form.getFormData('form_12')?.search;

    if (+type === 0) {
      queryManage.queryDrillNews(process, searchText).then(res => {
        panel.setData([{data: res}]);
        panel.render()
      })
    } else {
      queryManage.queryDrillGroup(type, process).then(res => {
        panel.setData([{data: res}]);
        panel.render()
      })
    }
  } else if (type === 'operation') {
    /**
     * 按钮事件
     */
    switch (operation.type) {
      case '再现': {
        openRecord()
        break;
      }
      case '评估':
        const assessWidget = this.getApiPage().getApiWidgetByAliasName('演练评估');
        const assessObj = assessWidget?.widgetObj;
        showAssessment((temp, isDetail) => {
          $(assessWidget.__box).removeAttr('data-status');
          assessObj._option.defaultData = data;
          assessObj?.renderFooter(isDetail && []);
          assessObj?.renderContent(temp);
          assessObj?.show();
        });
        break;
      case '总结': {
        const timeline = this.getApiPage().getApiWidgetByAliasName('timelineVertical');
        const summary = this.getApiPage().getApiWidgetByAliasName('summary').widgetObj;
        timeline.hideWidget();
        this.pageObj.setVariables([{ name: 'timeline_event_id', value: data.id }]);
        queryDrillDetail().then(detail => {
          console.log(detail);
          summary.option_dataSource.eventRecord.personCount = detail.personCount;
          // summary.eventInfoRender(summary.$detail);
          summary.render();
          summary.show();
          $('#summary .file-box').text(summary.fileName);
        });

        // window.parent.postMessage({ type: 'nav/style', pageName: '总结' }, document.referrer);
        break;
      }
      case '人员':
      case '明细': {
        const drillPersonWidget = this.getApiPage().getApiWidgetByAliasName('新增演练人员')?.widgetObj;
        showDrillDetail().then(res => {
          drillPersonWidget?.showDetail(res);
        });
        break;
      }
      case '详情': {
        showDrillDetail();
        break;
      }
      case '合并列表': {
        const eventTime = this.pageObj.getApiWidgetsByClassName('event-time');
        const merge_modals = this.pageObj.getApiWidgetsByClassName('event-merge');
        merge_modals.forEach(v => v.hideWidget());
        eventTime.forEach(v => v.showWidget());

        this.pageObj.setVariables([{ name: 'event_parentId', value: data.id }])
        break;
      }
      case '合并': {
        const merge_modals = this.pageObj.getApiWidgetsByClassName('event-merge');
        const eventTime = this.pageObj.getApiWidgetsByClassName('event-time');
        merge_modals.forEach(v => v.showWidget());
        eventTime.forEach(v => v.hideWidget());
        break;
      }
    }
  }
}catch (e) {
  console.error(e)
}
